package cn.casc.tools.er;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.logging.Logger;

/**
 * @author max
 * @version 1.0.1
 * @className SpecialRule
 * @description
 * @copyright Copyright (c) 2023
 * @company 天纲梦工厂
 * @datetime 2024/7/18 13:59
 **/
public class SpecialRule {
    final static Logger LOGGER = Logger.getLogger(SpecialRule.class.getName());
    // 通用字段忽略
    public Set<String> ignores = new HashSet<>();
    /** 别名字段
     * case ["xx_id"] 其它表
     * case ["a_id@type=a","b_id@type=b"] 条件id
     */
    public Map<String, List<String>> alias = new HashMap<>();
    public boolean isIgnore(ColumnItem col) {
        if(this.ignores.contains(col.column) || this.ignores.contains(col.getFullName())) {
            return true;
        }
        return false;
    }
    public List<String> getAliases(ColumnItem col) {
        List<String> alias = this.alias.get(col.getFullName());
        if(alias != null) {
            return alias;
        }
        alias = this.alias.get(col.column);
        if(alias != null) {
            return alias;
        }
        if(col.column.endsWith("_id")) {
            if(this.ignores.contains(col.column)) {
                return Collections.emptyList();
            }
            return Arrays.asList(col.column);
        } else {
            return Collections.emptyList();
        }
    }

    public static SpecialRule load() {
        try(FileInputStream fis = new FileInputStream("rule.json")) {
            return JSON.parseObject(fis, SpecialRule.class);
        } catch (Exception e) {
            LOGGER.fine(e.getMessage());
        }
        return new SpecialRule();
    }

    public void save() {

        try(FileOutputStream fos = new FileOutputStream("rule.json")) {
            JSON.writeJSONString(fos, this, SerializerFeature.PrettyFormat);
        } catch (Exception e) {
            LOGGER.fine(e.getMessage());
        }
    }
}